package com.puhui.lib.network.interceptors

import com.demo.kotlin.network.BaseNetworkCallBack
import okhttp3.Interceptor
import okhttp3.Response
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import kotlin.experimental.and

class RequestInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val original = chain.request()
        val builder = original.newBuilder().addHeader("api-key", "1122")
//        //有token，则加入header
//        val accessToken = SpUtilsKt.getAccessToken()
//        accessToken?.let { builder.addHeader("user-token", it) }
        val request = builder.build()

        //拦截response获取code，做统一处理
        val response = chain.proceed(request)
        val responseBody = response.body() ?: return response
        val source = responseBody.source()
        source.request(Long.MAX_VALUE)
        val buffer = source.buffer
        val charset = StandardCharsets.UTF_8
        val string = buffer.clone().readString(charset)
        try {
            val jsonObject = JSONObject(string)
            val code = jsonObject.optString("code")
            if (code != "200") {
                BaseNetworkCallBack.errorCode = code
            }
        } catch (e: JSONException) {
            e.printStackTrace()
            return response
        }

        return response
    }

    /**
     * 加密请求参数方式
     */
//    @Throws(IOException::class)
//    override fun intercept(chain: Interceptor.Chain): Response {
//        val original = chain.request()
//        val requestUrl = original.url()
//        val method = original.method()
//        val body = original.body()
//        var beforeMd5 = ""
//        val signSb = StringBuilder()
//        val signMap = HashMap<String, String>()
//        val keyList: MutableList<String> = ArrayList(10)
//
//        if ("POST" == method || "PUT" == method || "DELETE" == method) {
//            if (body is FormBody) {
//                for (i in 0 until body.size()) {
//                    signMap[body.name(i)] = body.value(i)
//                }
//            } else {
//                keyList.addAll(requestUrl.queryParameterNames())
//                for (i in keyList.indices) {
//                    signMap[keyList[i]] = requestUrl.queryParameterValue(i)
//                }
//                keyList.clear()
//            }
//        } else if ("GET" == method) {
//            keyList.addAll(requestUrl.queryParameterNames())
//            for (i in keyList.indices) {
//                signMap[keyList[i]] = requestUrl.queryParameterValue(i)
//            }
//            keyList.clear()
//        }
//
//        signMap["appversion"] = BuildConfig.VERSION_NAME
//        signMap["os"] = "android"
//        signMap["timestamp"] = System.currentTimeMillis().toString()
//        keyList.addAll(signMap.keys)
//        keyList.sort()
//        for (key in keyList) {
//            signSb.append(key).append(signMap[key])
//        }
//        val appkey = "49c152b75d6d213fa8521495371j48g3"
//        beforeMd5 = signSb.append(appkey).toString()
//        val afterMD5 = md5Sign(beforeMd5).toUpperCase(Locale.getDefault())
//        if (BuildConfig.DEBUG) {
//            LogUtils.loge("加密前：$beforeMd5")
//            LogUtils.loge("加密后：$afterMD5")
//        }
//
//        val builder = original.newBuilder()
//            .addHeader("api-key", Constant.API_KEY)
////            .addHeader("appversion", BuildConfig.VERSION_NAME)
////            .addHeader("os", "android")
////            .addHeader("timestamp", System.currentTimeMillis().toString())
////            .addHeader("sign", afterMD5)
//        //有token，则加入header
//        val accessToken = SpUtilsKt.getAccessToken()
//        accessToken?.let { builder.addHeader("user-token", it) }
//        val request = builder.build()
//
//        signMap.clear()
//        keyList.clear()
//
//        //拦截response获取code，做统一处理
//        val response = chain.proceed(request)
//        val responseBody = response.body() ?: return response
//        val source = responseBody.source()
//        source.request(Long.MAX_VALUE)
//        val buffer = source.buffer
//        val charset = StandardCharsets.UTF_8
//        val string = buffer.clone().readString(charset)
//        try {
//            val jsonObject = JSONObject(string)
//            val code = jsonObject.optString("code")
//            if (code != "200") {
//                BaseNetworkCallBack.errorCode = code
//            }
//        } catch (e: JSONException) {
//            e.printStackTrace()
//            return response
//        }
//
//        return response
//    }

    private fun md5Sign(source: String): String {
        try {
            val messageDigest: MessageDigest = MessageDigest.getInstance("md5")
            val result = messageDigest.digest(source.toByteArray())
            val md5Sb = StringBuilder()

            for (byte in result) {
                val number = byte and 0xff.toByte()
                val str = Integer.toHexString(number.toInt())
                if (str.length == 1) {
                    md5Sb.append("0")
                }
                md5Sb.append(str)
            }
            return md5Sb.toString()
        } catch (e: Exception) {
            return ""
        }
    }
}